﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebControls;
using System.Data;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Globalization;
using zevenseas.SharePoint.Solutions.FeatureBlocker.ApplicationPages;
using Microsoft.SharePoint.Utilities;

namespace zevenseas.SharePoint.Solutions.FeatureBlocker.ApplicationPages
{
    public class Settings : Microsoft.SharePoint.WebControls.LayoutsPageBase
    {
        protected Label uxFeatures;
        protected Label uxMessage;

        protected WebApplicationSelector uxWebApplicationSelector;
        protected SPGridView gridView;
        protected SPGridView gridViewBlocked;

        protected DVDropDownList uxScope;

        protected ToolBarButton uxInstallBlocker;
        protected ToolBarButton uxUninstallBlocker;
        protected ToolBarButton uxSaveConfig;

        protected RadioButton uxHide;
        protected RadioButton uxBlock;
        protected RadioButton uxRedirect;

        protected TextBox uxRedirectUrl;
        protected TextBox uxListUrl;

        protected ToolBar uxToolbarBlockedGrid;

        protected CheckBox uxFarmAdmin;

        private DataView featuresDataView;
        private DataView blockedFeaturesDataView;

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            BindData();
            base.Render(writer);
        }

        protected override void OnLoadComplete(EventArgs e)
        {
            bool blockerInstalled = false;

            if (uxWebApplicationSelector != null)
            {
                SPWebApplication webApplication = uxWebApplicationSelector.CurrentItem;

                try
                {
                    blockerInstalled = Convert.ToBoolean(GetWebProperty("Installed" + webApplication.Id.ToString(), SPContext.Current.Web.Properties));
                }
                catch (Exception) { }
            }

            if (!blockerInstalled)
            {
                uxMessage.Text = "Feature is not activated on this WebApplication!";
                gridView.Enabled = false;
                uxUninstallBlocker.Visible = false;
            }
            else
            {
                uxInstallBlocker.Visible = false;
            }

            base.OnLoadComplete(e);
        }

        public void InstallBlocker(object sender, EventArgs e)
        {
            SPWebApplication webApplication = uxWebApplicationSelector.CurrentItem;
            if (webApplication.JobDefinitions.GetValue<FeatureBlockerTimerJob>("FeatureBlockerTimerJob") == null)
            {
                FeatureBlockerTimerJob installFeatureJob = new FeatureBlockerTimerJob("FeatureBlockerTimerJob", webApplication, null, SPJobLockType.None);
                SPOneTimeSchedule schedule = new SPOneTimeSchedule(DateTime.Now);
                installFeatureJob.Schedule = schedule;
                installFeatureJob.Name = "FeatureBlockerTimerJob";
                installFeatureJob.Title = "FeatureBlockerTimerJob";
                installFeatureJob.Installing = true;
                installFeatureJob.Update();

                SetWebProperty("true", "Installed" + webApplication.Id.ToString(), SPContext.Current.Web.Properties);
            }
        }

        public void UninstallBlocker(object sender, EventArgs e)
        {
            SPWebApplication webApplication = uxWebApplicationSelector.CurrentItem;
            if (webApplication.JobDefinitions.GetValue<FeatureBlockerTimerJob>("FeatureBlockerTimerJob") == null)
            {
                FeatureBlockerTimerJob installFeatureJob = new FeatureBlockerTimerJob("FeatureBlockerTimerJob", webApplication, null, SPJobLockType.None);
                SPOneTimeSchedule schedule = new SPOneTimeSchedule(DateTime.Now);
                installFeatureJob.Schedule = schedule;
                installFeatureJob.Name = "FeatureBlockerTimerJob";
                installFeatureJob.Title = "FeatureBlockerTimerJob";
                installFeatureJob.Installing = false;
                installFeatureJob.Update();

                SetWebProperty("false", "Installed" + webApplication.Id.ToString(), SPContext.Current.Web.Properties);
            }


        }

        

        public void RefreshStatsClick(object sender, EventArgs e)
        {
            this.Page.Response.Redirect("/_admin/zs.FeatureBlocker/settings.aspx");
        }

        public void UnBlockLink(object sender, EventArgs e)
        {
            if (((base.Request != null) && (base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"] != null)) && !string.IsNullOrEmpty(base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"]))
            {
                SPWebApplication webApplication = uxWebApplicationSelector.CurrentItem;
                FeatureCollection featureCollection = webApplication.GetChild<FeatureCollection>("FeatureCollection");
                List<string> features = featureCollection.Features;

                string[] ids = base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"].ToString().Split(new Char[] { '#' });

                foreach (string id in ids)
                {
                    if (!string.IsNullOrEmpty(id))
                    {
                        features.Remove(id);
                    }
                }

                featureCollection.Features = features;
                featureCollection.Update();

            }
        }

        public void BlockLink(object sender, EventArgs e)
        {
            if (((base.Request != null) && (base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"] != null)) && !string.IsNullOrEmpty(base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"]))
            {
                SPWebApplication webApplication = uxWebApplicationSelector.CurrentItem;
                FeatureCollection featureCollection = webApplication.GetChild<FeatureCollection>("FeatureCollection" + uxScope.SelectedValue.ToString()); ;
                List<string> features = new List<string>();

                // If no settings previously created, create them now.    
                if (featureCollection == null)
                {
                    SPPersistedObject parent = webApplication;
                    featureCollection = new FeatureCollection("FeatureCollection"+uxScope.SelectedValue.ToString(), parent, Guid.NewGuid());
                    featureCollection.Update();
                }

                if (featureCollection.Features != null)
                {
                    features = featureCollection.Features;
                }


                string[] ids = base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"].ToString().Split(new Char[] { '#' });

                foreach (string id in ids)
                {
                    if (!string.IsNullOrEmpty(id))
                    {
                        features.Add(id);
                    }
                }
               
                featureCollection.Features = features;
                featureCollection.Update();
            }
        }      

        private void BindData()
        {
            try
            {
                GetAllFeatures(ref blockedFeaturesDataView, ref featuresDataView);

                if (uxScope != null)
                {
                    string rowFilter = string.Empty;
                    if (!string.IsNullOrEmpty(uxScope.SelectedValue.ToString()))
                    {
                        rowFilter = "Scope LIKE '*" + uxScope.SelectedValue + "*'";
                    }
                    else
                    {
                        rowFilter = "Scope LIKE '*" + SPFeatureScope.Site.ToString() + "*'";
                    }

                    blockedFeaturesDataView.RowFilter = rowFilter;
                    featuresDataView.RowFilter = rowFilter;
                }

                gridView.DataSource = featuresDataView;
                gridView.DataBind();

                gridViewBlocked.DataSource = blockedFeaturesDataView;
                gridViewBlocked.DataBind();

            }
            catch (Exception error)
            {

            }
        }

        public void GetAllFeatures(ref DataView blockedFeaturesView, ref DataView featuresView)
        {
            blockedFeaturesView = new DataView();
            featuresView = new DataView();


            DataTable featureTable = new DataTable();
            featureTable.Columns.Add("ID");
            featureTable.Columns.Add("Title");
            featureTable.Columns.Add("Description");
            featureTable.Columns.Add("Scope");
            featureTable.Columns.Add("Disallowed");

            DataTable blockedFeatureTable = new DataTable();
            blockedFeatureTable = featureTable.Clone();

            List<string> disallowedFeatures = new List<string>();
            disallowedFeatures = DisallowedFeatures(ref disallowedFeatures);

            try
            {
                foreach (SPFeatureDefinition featureDefinition in SPFarm.Local.FeatureDefinitions)
                {
                    if (!featureDefinition.Hidden)
                    {
                        
                        bool disallowed = false;

                        if (disallowedFeatures != null)
                        {
                            if (disallowedFeatures.Count > 0)
                            {
                                foreach (string disallowedFeature in disallowedFeatures)
                                {
                                    if (disallowedFeature == featureDefinition.Id.ToString())
                                    {
                                        disallowed = true;
                                        break;
                                    }
                                }
                            }
                        }

                        if (disallowed)
                        {
                            DataRow row = blockedFeatureTable.NewRow();
                            row["ID"] = featureDefinition.Id;
                            row["Title"] = featureDefinition.GetTitle(new CultureInfo(1033));
                            row["Description"] = featureDefinition.GetDescription(new CultureInfo(1033));
                            row["Scope"] = featureDefinition.Scope.ToString();
                            blockedFeatureTable.Rows.Add(row);
                        }
                        else
                        {
                            DataRow row = featureTable.NewRow();
                            row["ID"] = featureDefinition.Id;
                            row["Title"] = featureDefinition.GetTitle(new CultureInfo(1033));
                            row["Description"] = featureDefinition.GetDescription(new CultureInfo(1033));
                            row["Scope"] = featureDefinition.Scope.ToString();
                            featureTable.Rows.Add(row);
                        }
                    }
                }
            }
            catch (Exception ex)
            {

            }


            featuresView = new DataView(featureTable);
            featuresView.Sort = "Title";

            blockedFeaturesView = new DataView(blockedFeatureTable);
            blockedFeaturesView.Sort = "Title";

        }

        private List<string> DisallowedFeatures(ref List<string> disallowedFeatures)
        {
            SPWebApplication webApplication = uxWebApplicationSelector.CurrentItem;
            FeatureCollection settings = webApplication.GetChild<FeatureCollection>("FeatureCollection"+uxScope.SelectedValue.ToString());
            if (settings != null)
            {
                if (settings.Features != null)
                {                    
                    disallowedFeatures = settings.Features;
                }
            }

            return disallowedFeatures;
        }

        public static void SetWebProperty(string propertyValue, string propertyName, SPPropertyBag siteWebProperties)
        {
            string propertyname = "zs_" + propertyName;

            if (siteWebProperties[propertyname] == null)
            {
                siteWebProperties.Add(propertyname, propertyValue);
            }
            else
            {
                siteWebProperties[propertyname] = propertyValue;
            }
            siteWebProperties.Update();
        }

        public static string GetWebProperty(string propertyName, SPPropertyBag siteWebProperties)
        {
            string propertyname = "zs_" + propertyName;
            string returnvalue;

            if (siteWebProperties[propertyname] == null)
            {
                returnvalue = "";
            }
            else
            {
                returnvalue = siteWebProperties[propertyname];
            }

            return returnvalue;
        }
    }


}
